package netty.udp.demo4;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOption;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.kqueue.KQueue;
import io.netty.channel.kqueue.KQueueChannelOption;
import io.netty.channel.kqueue.KQueueDatagramChannel;
import io.netty.channel.kqueue.KQueueEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;

import java.net.InetSocketAddress;

/**
 * @program netty-demo
 * @description: https://netty.io/wiki/native-transports.html#wiki-h2-0
 * @author: zhanglu
 * @create: 2020-07-01 10:46:00
 */
public class UdpServer {

    public static void main(String[] args) {
        try {
            Bootstrap b = new Bootstrap();
            int cpuNum = Runtime.getRuntime().availableProcessors();
            System.out.println("cpu:" + cpuNum);
            KQueueEventLoopGroup group = new KQueueEventLoopGroup();
            b.group(group)
                    .channel(KQueueDatagramChannel.class)
                    .option(ChannelOption.SO_BROADCAST, true)
                    .option(ChannelOption.SO_RCVBUF, 1024 * 1024)
                    .handler(new UdpServerHandler());
            // linux平台下支持SO_REUSEPORT特性以提高性能
            if (KQueue.isAvailable()) {
                b.option(KQueueChannelOption.SO_REUSEPORT, true);
            }
            System.out.println(0);
            b.bind(7408).sync().channel().closeFuture();
            System.out.println(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
            System.out.println(2);
            ByteBuf buf = packet.copy().content();
            byte[] req = new byte[buf.readableBytes()];
            buf.readBytes(req);
            String body = new String(req, "UTF-8");
            System.out.println(body);//打印收到的信息
            //向客户端发送消息
            String json = "7408服务给我们平台发送消息";
            // 由于数据报的数据是以字符数组传的形式存储的，所以传转数据
            byte[] bytes = json.getBytes("UTF-8");
            DatagramPacket data = new DatagramPacket(Unpooled.copiedBuffer(bytes), new InetSocketAddress(8401));
            ctx.writeAndFlush(data);//向客户端发送消息
            System.out.println(3);
        }
    }


}
